<template>
  <div class="box sku-sale-collect">
    <div class="header">
      <div class="title">
        销售数据<span class="sub-title"
          >{{ datePickerFormat[0] }} ~ {{ datePickerFormat[1] }}</span
        >
      </div>
      <common-week-month-year @handleChange="handleRadioGroupSelChange" />
    </div>
    <div class="charts">
      <sku-sale-collect-line-chart
        id="amount-collect"
        title="销售额趋势图"
        :chart-option="lineChartOption"
        :loading="loading"
      />
      <sku-sale-collect-bar-chart
        id="region-collect"
        title="销售额分布"
        :chart-option="barChartOption"
        :loading="loading"
      />
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import dayjs from 'dayjs';
import CommonWeekMonthYear from '@/components/week-month-year/index.vue';
import SkuSaleCollectLineChart from './sku-sale-collect-line-chart.vue';
import SkuSaleCollectBarChart from './sku-sale-collect-bar-chart.vue';

// 定义变量
const datePickerSel = ref([]);
const datePickerFormat = ref(['2024.01.01', '2024.01.31']); // 初始化默认值
const radioGroupSel = ref('week');
const loading = ref(false); // 添加加载状态
const collectType = ref(1); // 统计时间类型，1:按日统计，2:按月统计

// 图表数据（响应式）
const lineChartOption = ref({
  xAxisData: [],
  seriesData: [],
  yAxisName: '单位：元',
});

const barChartOption = ref({
  xAxisData: [],
  seriesData: [],
  yAxisName: '单位：元',
  legendData: ['销售额'] //  为柱状图添加 legendData（如果需要）
});

// 模拟 API 请求（替换为实际请求）
const fetchChartData = async () => {
  loading.value = true;
  try {
    // 模拟 API 调用，替换为实际的 API
    // const { lineData, barData } = await api.getSalesData({
    //   startTime: datePickerFormat.value[0],
    //   endTime: datePickerFormat.value[1],
    //   type: collectType.value
    // });

    // 模拟数据（根据时间类型调整）
    const now = dayjs();
    const start = now.startOf(radioGroupSel.value);
    const end = now.endOf('day');

    // 模拟趋势图数据
    const lineXData = [];
    const lineYData = [];
    const days = end.diff(start, 'day') + 1;
    for (let i = 0; i < Math.min(days, 10); i++) { // 限制最多10个点
      lineXData.push(start.add(i, 'day').format('YYYY-MM-DD'));
      lineYData.push(Math.floor(Math.random() * 1000) + 500);
    }

    // 模拟分布图数据
    const barXData = ['北京平西府街道', '霍营街道', '朝阳区', '海淀区'];
    const barYData = barXData.map(() => Math.floor(Math.random() * 1000) + 300);

    lineChartOption.value = {
      xAxisData: lineXData,
      seriesData: lineYData,
      yAxisName: '单位：元'
    };

    barChartOption.value = {
      xAxisData: barXData,
      seriesData: barYData,
      yAxisName: '单位：元',
      legendData: ['销售额']
    };
  } catch (error) {
    console.error('获取销售数据失败:', error);
    // 可在此处添加用户提示
    // ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 处理时间范围变化
const handleRadioGroupSelChange = (radioGroup) => {
  radioGroupSel.value = radioGroup;

  // 根据选择更新时间范围
  const startFormat = dayjs().startOf(radioGroup).format('YYYY.MM.DD');
  const endFormat = dayjs().endOf('day').format('YYYY.MM.DD');
  datePickerFormat.value = [startFormat, endFormat];

  // 更新统计类型（根据选择）
  collectType.value = radioGroup === 'day' ? 1 : 2; // 假设 day=按日，week/month=按月

  // 触发数据刷新
  fetchChartData();
};

onMounted(() => {
  handleRadioGroupSelChange(radioGroupSel.value);
});
</script>

<style lang="scss" scoped>
.sku-sale-collect {
  display: flex;
  flex-direction: column;
  height: calc((100vh - 120px) * 0.4 - 20px);
  min-height: 352px;
  margin-top: 20px;
  background: #FFFFFF;
  border-radius: 20px;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px;
    border-bottom: 1px solid #eee;

    .title {
      font-size: 16px;
      font-weight: bold;
      color: #333;

      .sub-title {
        margin-left: 8px;
        font-size: 14px;
        font-weight: normal;
        color: #999;
      }
    }
  }

  .charts {
    flex: 1;
    display: flex;

    // 为两个图表分配空间
    :deep(.sku-sale-collect-line-chart),
    :deep(.sku-sale-collect-bar-chart) {
      flex: 1;
      min-width: 0; // 防止溢出
    }
  }
}
</style>